/*
 * @Author: LiuYan
 * @Date: 2022-11-14 21:18:09
 * @LastEditors: LiuYan
 * @LastEditTime: 2022-12-20 10:38:54
 * @Description 自定义样式的Tabs
 */
export default class Tabs {
  /**
   * @description: 在css中 可以通 .yik_tabs_active{} class 自定义激活样式，如果各别属性不生效使用请使用权重（如：width: 10px !important）
   * @param {*} tabs 获取容器元素  必填
   * @param {*} tabsItem 获取容器子元素 必填
   * @param {*} index 激活第几个元素 默认:0
   * @param {*} gap 间隔多少px 可以写正负值  例：+1 -1  默认：0
   * @param {*} ms 激活滑动所需的秒数 默认：0.5
   * @param {*} watch 回调函数 返回当前下标下元素的宽高和当前下标值，以及返回当前激活元素dom
   * @return {*} setActive(0) 方法调用
   */
  constructor({
    tabsEl,
    tabsItemEl,
    index = 0,
    gap = 0,
    ms = 0.3,
    watch = () => {},
  }) {
    this.tabs = document.querySelector(tabsEl);
    this.tabsItem =
      typeof tabsItemEl === "string"
        ? document.querySelectorAll(tabsItemEl)
        : tabsItemEl;
    this.tabsActive = null;
    this.index = index;
    this.gap = gap;
    this.ms = ms;
    this.watch = watch;
    this.initTabsStyle();
    this.initTabsActive();
    this.onClick();
  }
  //初始化容器样式
  initTabsStyle() {
    this.tabs.style.position = "relative";
    this.tabs.style.display = "flex";
  }
  //初始化容器激活样式
  initTabsActive() {
    this.tabsActive = document.createElement("div");
    this.tabsActive.className = "yik_tabs_active";
    this.tabs.appendChild(this.tabsActive);
    this.tabsActive.style.position = "absolute";
    this.tabsActive.style.left = 0 + this.gap + "px";
    this.tabsActive.style.transition =
      "left " + this.ms + "s" + ",width " + this.ms + "s";
    this.tabsActive.style.height = "4px";
    this.tabsActive.style.background = "#3E7BFA";
    this.setActive(this.index);
  }
  // 点击事件
  onClick() {
    this.tabsItem.forEach((item, index) => {
      item.addEventListener("click", (e) => {
        this.index = index;
        this.setActive(index);
      });
    });
  }
  // 激活元素
  setActive(index) {
    let item = this.tabsItem[index];
    let left =
      item.getBoundingClientRect().left -
      this.tabs.getBoundingClientRect().left;
    this.tabsActive.style.width =
      item.getBoundingClientRect().width + this.gap + "px";
    this.tabsActive.style.left = left + this.gap + "px";
    this.index = index;
    this.onWatchTab(item, left + this.gap);
  }
  // 执行回调
  onWatchTab(item, left) {
    if (typeof this.watch == "function" && this.watch) {
      this.watch({
        item: {
          width: item.getBoundingClientRect().width,
          height: item.getBoundingClientRect().height,
          el: item,
        },
        all: this.tabsItem,
        active: this.tabsActive,
        index: this.index,
        left,
      });
    } else {
      throw new Error("watch必须是一个回调函数");
    }
  }
}
